package com.turman.builibrary.refresh;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.turman.builibrary.R;


public class BTextOverView extends BOverview {
    private TextView text;
    private View rotateView;

    private Runnable[] runnable;

    private int lastScrollY = -1;

    private Handler handler = new Handler(Looper.getMainLooper());
    public BTextOverView(@NonNull Context context) {
        super(context);
    }

    public BTextOverView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public BTextOverView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.b_refresh_text_overview, this, true);
        text = findViewById(R.id.loading_text);
        rotateView = findViewById(R.id.iv_image);
        //一下实现一种简单的跟手旋转效果
        runnable = new Runnable[1];
        runnable[0] = ()->{
            int move = getBottom();
            rotateView.setRotation(move);
            handler.postDelayed(runnable[0],100);
        };
    }

    @Override
    protected void onScroll(int scrollY, int pullRefreshHeight) {
        if (scrollY > lastScrollY) {
            handler.postDelayed(runnable[0], 100);
        }
        lastScrollY = scrollY;
    }

    @Override
    protected void onVisible() {
        text.setText("下拉刷新");
    }

    @Override
    public void onOver() {
        text.setText("松开刷新");
    }

    @Override
    public void onRefresh() {
        text.setText("正在刷新...");
        Animation operationAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_anim);
        LinearInterpolator linearInterpolator = new LinearInterpolator();
        operationAnimation.setInterpolator(linearInterpolator);
        rotateView.startAnimation(operationAnimation);
    }

    @Override
    public void onRefreshFinished() {
        rotateView.clearAnimation();
    }
}
